package com.skywork.controller.base;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestParam;

import com.skywork.controller.advice.MyRequestWrapper;
import com.skywork.controller.exception.RestException;
import com.skywork.domain.AccessToken;
import com.skywork.domain.Channel;
import com.skywork.domain.base.ActiveFlag;
import com.skywork.service.AccessTokenService;
import com.skywork.service.ChannelService;
import com.skywork.utils.ChannelKit;
import com.skywork.utils.SignUtil;

public class BaseController {

	protected final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private AccessTokenService accessTokenService;
	@Autowired
	private ChannelService channelService;

	@ModelAttribute
	public void getChannel(@RequestParam(value = "token") String token, @RequestParam(value = "timestamp") Long timestamp, @RequestParam(value = "sign") String sign, HttpServletRequest request) {

		AccessToken accessToken = accessTokenService.findByToken(token);
		if (accessToken == null) {
			throw new RestException(HttpStatus.UNAUTHORIZED, "Token Error");
		}
		if (accessToken != null) {
			Channel channel = channelService.selectByPrimaryKey(accessToken.getChannelId());
			if (channel != null && ActiveFlag.ACTIVE.equals(channel.getActiveFlag())) {
				String body = "";

				try {
					MyRequestWrapper myRequestWrapper = new MyRequestWrapper(request);
					InputStream in = myRequestWrapper.getInputStream();
					body = StreamUtils.copyToString(in, Charset.forName("UTF-8"));
				} catch (IOException e) {
					e.printStackTrace();
				}
				StringBuffer signStr = new StringBuffer();
				signStr.append(StringUtils.isBlank(body) ? "" : body).append(channel.getPassword()).append(timestamp);
				if (!SignUtil.checkSignature(body, channel, timestamp, sign)) {
					throw new RestException(HttpStatus.BAD_REQUEST, "Sign Error");
				}

				ChannelKit.setThreadLocalChannel(channel);
			} else {
				throw new RestException(HttpStatus.UNAUTHORIZED, "Channel Error");
			}

		}
	}
}
